/**
 * 
 */
package jvs.peer.xmpp;

import java.security.Principal;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Vector;

import jvs.peer.sec.Group;
import jvs.peer.sec.User;

import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.RosterGroup;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;


/**
 *
 * @author qiangli
 * 
 */
public class XmppPeerGroup extends Group {

	private static final long serialVersionUID = 1L;
	private XMPPConnection conn;
	//private String name;

	XmppPeerGroup(String name, XMPPConnection conn) {
		this.name = name;
		this.conn = conn;
	}
	
	private Roster getRoster() {
		if (conn.isConnected()) {
			return conn.getRoster();
		} else {
			try {
				conn.connect();
			} catch (XMPPException e) {
				//TODO retry ?
				e.printStackTrace();
			}
			return conn.getRoster();
		}
	}


	public boolean addMember(Principal user) {
		Roster r = getRoster();
		RosterGroup rg = r.getGroup(name);
		User p = (User) user;
		RosterEntry re = r.getEntry(p.getId());
		try {
			if (re == null) {
				r.createEntry(p.getId(), p.getName(), new String[] { name });
			} else {
				rg.addEntry(re);
			}
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}


	public boolean isMember(Principal member) {
		Roster r = getRoster();
		RosterGroup rg = r.getGroup(name);
		User p = (User) member;
		return rg.contains(p.getId());
	}


	public Enumeration<? extends Principal> members() {
		Roster r = getRoster();
		RosterGroup rg = r.getGroup(name);
		Collection<RosterEntry> gc = rg.getEntries();
		if (gc == null) {
			return null;
		}
		Vector<Principal> v = new Vector<Principal>();
		for (RosterEntry re : gc) {
			Principal p = new XmppPeerPrincipal(re.getUser(), re.getName());
			v.add(p);
		}
		return v.elements();
	}


	public boolean removeMember(Principal user) {
		Roster r = getRoster();
		RosterGroup rg = r.getGroup(name);
		User p = (User) user;
		RosterEntry re = r.getEntry(p.getId());
		if (re == null) {
			return false;
		}
		try {
			rg.removeEntry(re);
			return true;
		} catch (XMPPException e) {
			e.printStackTrace();
		}
		return false;
	}
}
